package es.uclm.itsue.internet;

import java.io.IOException;
import java.io.InputStream;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class JSONActivity extends Activity {

   	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

        InputStream is = this.getResources()
        		.openRawResource(R.raw.jsonfile);
        byte[] buffer;
		try {
			buffer = new byte[is.available()];
	        while (is.read(buffer) != -1);
	        String text = new String(buffer);
//	        Log.i("JSON", "Texto del fichero: " + text);
	        parseJSONString(text);
		} 
		catch (IOException e) {
        	Log.e("JSON","Error leyendo fichero:\n" 
        			+ e.getMessage());
		}
	}
   	
   	void parseJSONString(String str)
    {
        try
        {
            JSONArray profs = new JSONArray(str);
            String x = "Encontrados " + profs.length() + " profesores:\n\n";

            for (int i=0; i<profs.length(); i++)
            {
                JSONObject prof = profs.getJSONObject(i);
                x += "------------\n";
                x += prof.getString("firstName") + " " + prof.getString("lastName") + "\n";
                JSONObject address = prof.getJSONObject("address");
                x += "Despacho: " 
                		+ address.getString("building") + "("
                		+ address.getString("office") + ")" + "\n";
                x += "Telefono: " + prof.getString("phone") + "\n";
            }
            Log.i("JSON",x);
        }
        catch (Exception ex)
        {
        	Log.e("JSON","Error: " + ex.getMessage());
        }
    }
}
